package com.hqyj.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hqyj.dao.UserInfoMapper;
import com.hqyj.pojo.UserInfo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class MyRealm extends AuthorizingRealm {


    @Resource
    UserInfoMapper userInfoMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户凭证
        UsernamePasswordToken myToken = (UsernamePasswordToken)authenticationToken;
        //获取登录的用户名
        String userName = myToken.getPrincipal()+"";
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        //查询用户
        UserInfo userInfo =userInfoMapper.selectOne(queryWrapper);

        //判断用户名是否正确
        if(userInfo==null){
            throw new UnknownAccountException();
        }
        //密码验证
        AuthenticationInfo auth = new SimpleAuthenticationInfo(
                userInfo.getUserName(), userInfo.getUserPwd(),new Md5Hash(userInfo.getUserSalt()),this.getName());

        return auth;
    }
}
